package com.bdqn.controller;


import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;
import com.bdqn.utils.Constants;
import com.bdqn.utils.PageSupport;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysRoleService sysRoleService;

    @PostMapping("/login")
    public String doLogin(RuntimeException e,HttpServletRequest request, HttpSession session, @RequestParam String account, @RequestParam String password){
        logger.debug("登录方法");
        SysUser sysUser = sysUserService.getAccount(account,password);
        if (null != sysUser){
            session.setAttribute(Constants.USER_SESSION,sysUser);
            session.setAttribute("USER_SESSION",sysUser);
            return "redirect:/user/toMain";
        }else {
            session.setAttribute("error","账号或密码错误");
            return "login";
        }

    }

    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> userList = null;
        List<SysRole> sysRoles = null;
        try{
            //设置页面容量
            int pageSize = Constants.pageSize;
            //总数量
            int totalCount = sysUserService.getCount();
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex); // 设置当前页数
            pages.setPageSize(pageSize);       // 设置一页显示数据量
            pages.setTotalCount(totalCount);   // 设置总数据量
            int totalPageCount = pages.getTotalPageCount();

            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList((pageIndex-1)*pageSize,pageSize,queryRealName,queryRoleId);
            sysRoles = sysRoleService.getAll();
            model.addAttribute("userList",userList);  // 用户信息

            model.addAttribute("totalCount",pages.getTotalCount()); // 分页信息
            model.addAttribute("currentPageNo",pages.getPageNo());
            model.addAttribute("totalPageCount",pages.getTotalPageCount());

            model.addAttribute("queryRealName",queryRealName); // 查询条件回显
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("roleList",sysRoles);



        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "/sysUser/list";
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/checkOldPwd",produces = {"application/json;charset=UTF-8"})
    public String getPwd(String oldPassword, HttpServletResponse response,HttpSession session) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        // 查询输入密码是否和数据库用户密码相同
        String account = sysUser.getAccount();
        int pwd = sysUserService.getPwd(oldPassword,account);
        Map<String,String> map = new HashMap<>();
        String result = "true";
        // 判断是否与旧密码相同 true:成功 false:失败
        if (pwd == 1){
            result = "true";
        }else {
            result = "false";
        }

        map.put("result",result);
        return JSON.toJSONString(map);
    }
    @ResponseBody // 让返回的内容原样输出到页面（通常用于ajax处理）
    @PostMapping(value = "/savePassword",produces = "text/html; charset=UTF-8")
    public String savePassword(String newPassword,HttpSession session,HttpServletResponse response) throws IOException {
        // 获取登录账号的用户信息
        SysUser sysUser = (SysUser)session.getAttribute(Constants.USER_SESSION);
        // 调用方法修改密码
        int iRet = sysUserService.savePassword(sysUser.getAccount(),newPassword);

        String result = null;
        if (iRet == 1){
            result = "<script>alert('修改密码成功！');window.location='http://localhost:8080/724_war_exploded/user/toUpdatePwd'</script>";
        }else{
            result = "<script>alert('修改密码失败！');window.location='http://localhost:8080/724_war_exploded/user/toUpdatePwd'</script>";
        }

        return result;
    }

    @ResponseBody  // 让返回的内容原样输出到页面（通常用于ajax处理）
    @GetMapping(value = "/userExist")
    public String getAccountC(String account){
        // 查询是否有相同的账号
        int accountC = sysUserService.getAccountC(account);
        Map<String,Integer> map = new HashMap<>();
        if (accountC > 1){
            map.put("exist", 1);
        }else if (accountC == 0){
            map.put("exist", 0);
        }
        return JSON.toJSONString(map);
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    // 退出
    @RequestMapping("/logout")
    public String tui(HttpSession session){
        session.removeAttribute("USER_SESSION");
        session.invalidate();
        return "login";
    }
    @GetMapping("/add")
    public String toAdd(){ return "/sysUser/add"; }
    @GetMapping("/toUpdatePwd")
    public String toUpdatePwd(){
        return "/sysUser/updatePassword";
    }

    @RequestMapping(value = "/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    // 跳转到登录页面
    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }
}
